<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="字段别名" prop="fieldAlias">
        <el-input
          v-model="queryParams.fieldAlias"
          placeholder="请输入字段别名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="表名" prop="tableName">
        <el-input
          v-model="queryParams.tableName"
          placeholder="请输入表名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Plus"
          @click="handleInitializationField"
          v-hasPermi="['lowcode:model:add']"
        >初始化</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="fieldList">
      <!-- <el-table-column label="字段名称" align="center" prop="fieldName" /> -->
      <!-- <el-table-column label="字段全名" align="center" prop="fieldTableAliasName" /> -->
      <el-table-column label="字段别名" align="center" prop="fieldAlias" />
      <el-table-column label="表名" align="center" prop="tableName" />
      <el-table-column label="显示名称" align="center" prop="remark">
        <template #default="scope">
          <el-input v-model="scope.row.remark" @blur="handleUpdate(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="主键" align="center" prop="isId">
        <template #default="scope">
          <el-switch 
            v-model="scope.row.isId" 
            @change="handleUpdate(scope.row)"
            active-value="1"
            inactive-value="0" />
        </template>
      </el-table-column>
      <el-table-column label="查询" align="center" prop="isQuery">
        <template #default="scope">
          <el-switch 
            v-model="scope.row.isQuery" 
            @change="handleUpdate(scope.row)"
            active-value="1"
            inactive-value="0" />
        </template>
      </el-table-column>
      <el-table-column label="搜索" align="center" prop="isSearch">
        <template #default="scope">
          <el-switch 
            v-model="scope.row.isSearch" 
            @change="handleUpdate(scope.row)"
            active-value="1"
            inactive-value="0" />
        </template>
      </el-table-column>
      <el-table-column label="图片" align="center" prop="isPicture">
        <template #default="scope">
          <el-switch 
            v-model="scope.row.isPicture" 
            @change="handleUpdate(scope.row)"
            active-value="1"
            inactive-value="0" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="空值" align="center" prop="isEmpty">
        <template #default="scope">
          <el-switch 
            v-model="scope.row.isEmpty" 
            @change="handleUpdate(scope.row)"
            active-value="1"
            inactive-value="0" />
        </template>
      </el-table-column> -->
      <el-table-column label="搜索类型" align="center" prop="selectType">
        <template #default="scope">
          <el-select v-model="scope.row.selectType"
            :disabled="scope.row.dictionaryId != null"
           @change="handleUpdate(scope.row)" placeholder="请选择">
            <el-option
              v-for="item in lc_field_select_type"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="数据字典" align="center" prop="dictionaryId">
        <template #default="scope">
          <el-select v-model="scope.row.dictionaryId" @change="handleUpdate(scope.row, 1)" placeholder="请选择">
            <el-option
              v-for="item in dictionaryList"
              :key="item.dictionaryId"
              :label="item.dictionaryName"
              :value="item.dictionaryId"
            />
          </el-select>
        </template>
      </el-table-column>
      <!-- <el-table-column label="主表名称" align="center" prop="modelName" /> -->
      <!-- <el-table-column label="主表字段" align="center" prop="modelFieldId" /> -->
      <el-table-column label="父模型" align="center" prop="parentModelName" />
      <el-table-column label="父模型字段" align="center" prop="parentModelFieldAlias" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
              <el-button link type="primary" icon="Edit" @click="handleUpdateparentModel(scope.row)">维护</el-button>
          </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 修改子模型对话框 -->
    <el-dialog title="子模型维护" v-model="openparentModel" width="800px" append-to-body>
      <el-form ref="parentModelRef" :model="fieldparentModelInfo" :rules="rules" label-width="120px">

        <el-form-item label="父模型名称" prop="parentModelId">
          <el-select
            v-model="fieldparentModelInfo.parentModelId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入模型名称"
            remote-show-suffix
            :remote-method="modelRemoteMethod"
            :loading="parentModelIdLoading"
            @change="HandleParentModelChange"
          >
            <el-option
              v-for="item in selectModelList"
              :key="item.modelId"
              :label="item.modelName"
              :value="item.modelId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="父模型字段" prop="parentModelFieldId">
            <el-select v-model="fieldparentModelInfo.parentModelFieldId" placeholder="请选择">
              <el-option
                v-for="item in selectFieldList"
                :key="item.fieldId"
                :label="item.fieldAlias"
                :value="item.fieldId"
              ></el-option>
            </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="parentModelSubmitForm">确 定</el-button>
          <el-button @click="parentModelCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="Field">
import { listField, getField, delField, addField, updateField, queryFieldList } from "@/api/lowcode/field";
import { listDictionaryAll } from "@/api/lowcode/dictionary";
import { initializationField, queryModelList } from "@/api/lowcode/model";
import { toRefs } from 'vue'
import { ElMessageBox } from 'element-plus'

const { proxy } = getCurrentInstance();

const { lc_field_select_type } = proxy.useDict(
  "lc_field_select_type"
);

const props = defineProps({
  modelId: String,
})

const { modelId } = toRefs(props)

const fieldList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const dictionaryList = ref([]);
const openparentModel = ref(false)
const fieldInfo = ref(null)
const fieldparentModelInfo = ref(null)
const buttonLoading = ref(false)
const parentModelIdLoading = ref(false)
const selectModelList = ref([])
const selectFieldList = ref([])

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    modelId: undefined,
    fieldName: undefined,
    fieldTableAliasName: undefined,
    fieldAlias: undefined,
    tableName: undefined,
    isId: undefined,
    isQuery: undefined,
    isSearch: undefined,
    isEmpty: undefined,
    dictionaryId: undefined,
    modelName: undefined,
    modelFieldId: undefined,
  },
  rules: {
    parentModelId: [
      { required: true, message: "子模型名称不能为空", trigger: "change" }
    ],
    parentModelFieldId: [
      { required: true, message: "子模型字段不能为空", trigger: "change" }
    ]
  }
});

const { queryParams, rules } = toRefs(data);

/** 查询数据字典列表 */
function getDictionaryList() {
  listDictionaryAll().then(response => {
    dictionaryList.value = response.data;
  });
}

/** 查询模型字段列表 */
function getList() {
  loading.value = true;
  queryParams.value.modelId = modelId.value
  listField(queryParams.value).then(response => {
    fieldList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 初始化 */
function handleInitializationField(){
  initializationField(modelId.value).then(response => {
    handleQuery();
  })
}

/** 修改按钮操作 */
function handleUpdate(row, type) {
  if(type){
    row.selectType = 'EQUAL'
  }
  updateField(row).then(response => {
    proxy.$modal.msgSuccess("修改成功");
  });
}

/** 修改字段关联模型 */
function handleUpdateparentModel(row){
  fieldInfo.value = row
  fieldparentModelInfo.value = {
    parentModelId: null,
    parentModelFieldId: null
  }
  proxy.resetForm("parentModelRef");
  openparentModel.value = true
}

/** 修改字段关联模型保存 */
function parentModelSubmitForm(){

  ElMessageBox.confirm(
    '如果未选择模型，将会覆盖原设置模型，是否要继续？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      fieldInfo.value.parentModelId = fieldparentModelInfo.value.parentModelId
      fieldInfo.value.parentModelFieldId = fieldparentModelInfo.value.parentModelFieldId
      updateField(fieldInfo.value).then(response => {
        proxy.$modal.msgSuccess("修改成功");
        openparentModel.value = false
        getList()
      });
    })
}

function parentModelCancel(){
  openparentModel.value = false
}

function modelRemoteMethod(keyword){
  if(!keyword){
    return
  }
  queryModelList({ modelName: keyword }).then(response => {
    selectModelList.value = response.data
  })
}

function HandleParentModelChange(val){
  fieldparentModelInfo.value.parentModelFieldId = undefined
  queryFieldList({ modelId: fieldparentModelInfo.value.parentModelId }).then(response => {
    selectFieldList.value = response.data
  })
}

getList();
getDictionaryList();
</script>
